import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import DataGrid, { Column, Item, Toolbar } from 'devextreme-react/data-grid';
import { useModel } from 'umi';
import PubSub from 'pubsub-js';
import { getMomentMonthSjnd, getWindowsMapsList, intl } from '@/utils';
import SelZcbfPopup from './SelZcbfPopup';
import NewLocalProject from './NewLocalProject';
import { CpasIcon } from '~/public/cpas-ui';
import {
  getProjectList,
  getProjectZcbfAndUser, updateZcbfDelName, updateProjectZcbfAndUser, insertZcbfData, getZcbfList, syncProjectZcbf, getIsCheckProjectIsOpened
} from './service';
import notify from 'devextreme/ui/notify';
import './index.less';
import DropDownButton, { Item as ButtonItem } from 'devextreme-react/drop-down-button';
import InputOKDialog from '../components/InputOKDialog';
import moment from 'moment';
import LoadIndicator from 'devextreme-react/load-indicator';
import { getFrameworkVersion } from '@/services/cpasRequest';
import { Button } from 'devextreme-react/button';
import '@/pages/components/StyleFile/btnStyle.less';
import { delectZcbfPeriod, updateZcbfPeriod } from './NewLocalProject/service';
import { getPeriodList } from '../components/InitializePopup/service';
import { Popover } from 'antd';
import { getPeriodInfo } from '../tools/service';


const SelZcbfPopupMemo = memo(SelZcbfPopup);

const ProjectArea = () => {
  const { initialState } = useModel('@@initialState');
  const { curUser } = initialState || {};
  const selZcbfPopupRef = useRef<any>();
  const localFormRef = useRef<any>();
  const refsInputDialog = useRef<any>();
  const [appearanceData, setAppearanceData] = useState<any>([]);
  const [popupTitle, setPopupTitle] = useState<string>('');
  const refProject = useRef<any>();
  const [showSpin, setShowSpin] = useState<boolean>(false);
  const [iconBtn, setIconBtn] = useState<boolean>(true);

  const [selRowKey, setSelRowKey] = useState<any>([]);



  // 数据传递
  const getList = useCallback(async () => {
    setShowSpin(true);
    const res = await getProjectList();
    if (res.success) {
      setAppearanceData(res.data);
      setShowSpin(false);
    }
  }, []);

  useEffect(() => {
    if (curUser?.usercode) {
      getList();
    }
  }, [curUser, getList]);

  const onSelectionData = useCallback(async ({ selectedRowsData }: any) => {
    if (selectedRowsData[0]) {
      setSelRowKey([selectedRowsData[0]?.sjxmbh ?? '']);
      PubSub.publish('projectInfo', { msg: 'projectInfoData', data: selectedRowsData[0] });
    }
  }, []);

  PubSub.unsubscribe('projectTreeRefresh');
  PubSub.subscribe('projectTreeRefresh', async (msg: any, data: any) => {
    // console.log(data.msg);
    if (data.msg === 'projectRefresh') {
      await getList();
      if (data.xmbh) {
        await refProject.current.instance.selectRows([data.xmbh.split('【')[1].split("】")[0]],true)
      }
    }
  });


  const getZcbfID = async (proSjxmbh: any) => {
    const res = await getZcbfList({
      projectBh: proSjxmbh
    });
    if (res.success) {
      let selectedID: any = [];
      res.data.forEach((item: any) => {
        if (item.zcbfzt === 1) {
          selectedID.push(item.zcbfid);
        }
      });
      return {
        ok: true,
        data: selectedID
      }
    }
    return {
      ok: false,
      data: []
    }
  }


  // 最后更新Period_string的表
  const updatePeriod = async (element: any, proDBName: string) => {
    const resPer = await getPeriodList({
      zcbfID: element.zcbfID,
      dbName: proDBName
    });
    if (resPer.success) {
      if (resPer.data?.length) {
        const del = await delectZcbfPeriod({ dbName: element.zcbfID });
        if (del.success) {
          resPer.data.forEach(async (els: any) => {
            let moothStr = '';
            moothStr = getMomentMonthSjnd(els.ADateS, els.ADateE);
            const tempOBJ = { ...els, dbName: element.zcbfID, sjnd: moothStr }
            const resPeriod = await updateZcbfPeriod(tempOBJ);
            console.log('@@@', els, tempOBJ);
            if (resPeriod.success) {
              getPeriodInfo({ dbname: element.zcbfID });
            } else {
              notify({ message: `getPeriodInfo失败！`, position: 'top center', width: 300 }, "error", 1000);
            }
          });
        }
      }
    }
  }


  // 项目同步
  const projectSynchronize = async (rowData: any) => {
    const projectCode = rowData.projectBh.toString();
    const { data: localZcbfData } = await getZcbfList({
      projectBh: projectCode
    });
    const res = await getProjectZcbfAndUser({ projectCode: projectCode });
    if (res.success) {
      const resName = await updateZcbfDelName({ projectCode });
      if (resName.success) {
        const resProject = res.data['ljjx.pm.projectInfo'];
        const resUserAll = res.data['ljjx.pm.sjxmUserInfo'];
        const zcbfDataAll = res.data['ljjx.pm.zcbfInfo'];
        const projectDBName = resProject.data.serDBName; // 项目的DBName
        const updataProject = [{ ...resProject.data, rowState: 'update', where: { sjxmbh: projectCode } }];
        const updataDelUser: any[] = zcbfDataAll.data.map((el: { zcbfID: any; }) => {
          return {
            rowState: "delete",
            zcbfID: el.zcbfID
          }
        });
        const updataZcbf = zcbfDataAll.data.map((el: { zcbfID: any; }) => {
          return {
            ...el,
            rowState: 'update', where: { zcbfid: el.zcbfID }
          }
        });

        const zcbfIDDatas = zcbfDataAll.data.map((el: { zcbfID: string; sjnd: string; xmqjs: string; xmqje: string; }) => {
          return {
            zcbfID: el.zcbfID,
            sjnd: el.sjnd,
            ADateS: el.xmqjs,
            ADateE: el.xmqje,
            Data_ID: el.sjnd,
            dbName: el.zcbfID
          }
        })
        // syncProjectZcbf
        let updataAllUser = [...updataDelUser, {
          rowState: "delete",
          zcbfID: projectCode
        }, ...resUserAll.data];
        if (resProject.ok && zcbfDataAll.ok && resUserAll.ok) {
          const resInsert = await updateProjectZcbfAndUser(updataProject, updataAllUser, updataZcbf);
          if (resInsert.success) {
            const zcbfData: any[] = zcbfDataAll.data;
            const zcbfIDLocals = localZcbfData.map((item: any) => {
              return item.zcbfid;// 本地返回值为 zcbfID
            }).join(';');
            // 新增加的数据
            let addZcbfData = zcbfData.filter((item: any) => {
              const isNameInfo = !zcbfIDLocals.includes(item.zcbfID);
              return isNameInfo && item;
            });
            if (addZcbfData.length > 0) {
              const version = await getFrameworkVersion();
              const addNewZcbfData = addZcbfData.map((el) => {
                return {
                  ...el,
                  version,
                  zcbfzt: 0,
                  EditUser: curUser?.usercode,
                  EditDate: moment().format('YYYY-MM-DD HH:mm:ss')
                }
              });
              const insertZcbfRes = await insertZcbfData(addNewZcbfData);
              if (insertZcbfRes.success) {
                await getList();
                notify({ message: "同步成功！", position: 'top center' }, "success", 1000);
                PubSub.publish('projectInfo', { msg: 'projectInfoData', data: { ...rowData, projectAsync: Math.random() } });
              } else {
                notify({ message: "请求报错!", position: 'top center' }, "error", 1000);
              }
            } else {
              await getList();
              notify({ message: "同步成功！", position: 'top center' }, "success", 1000);
              PubSub.publish('projectInfo', { msg: 'projectInfoData', data: { ...rowData, projectAsync: Math.random() } });
            }
            zcbfIDDatas.forEach(async (elID: { zcbfID: string }) => {
              const ayncRes = await syncProjectZcbf({ zcbfID: elID.zcbfID, projectCode });
              if (!ayncRes) {
                notify({ message: "同步项目库失败", position: 'top center' }, "success", 1000);
              }
            });

            // 最后更新Period_string的表
            zcbfIDDatas.forEach(async (els: any) => {
              updatePeriod(els, projectDBName);
            });
          }
        } else {
          notify({ message: "请求报错!", position: 'top center' }, "error", 1000);
        }
      } else {
        notify({ message: "请求报错!", position: 'top center' }, "error", 1000);
      }
    } else {
      notify({ message: "请求报错!", position: 'top center' }, "error", 1000);
    }
    setIconBtn(true);
  }


  const renderClick = (row: any) => {
    if (!row.projectBh) return;
    if (row.XMType === '单机审计项目') {
      setPopupTitle('编辑单机建项');
      localFormRef.current.showForm(true, row);
    } else {
      if (iconBtn) {
        projectSynchronize(row);
        setIconBtn(false);
      } else {
        notify({ message: `项目【${row.projectName}】正在更新中！`, position: 'top center' }, "warning", 1000);
      }
    }
  }

  const renderCpasIcon = (rowData: any) => {

    const { data } = rowData;
    if (data.XMType === '单机审计项目') {
      return (<Popover content='编辑单机项目' placement="left">
        <div className='hoverBac'>
          <CpasIcon type='icon-rename-copy' fontSize={16}
            onClick={() => renderClick(data)} />
        </div>
      </Popover>)
    }
    return (<Popover content='更新项目信息' placement="left">
      <div className='hoverBac'>
        <CpasIcon type='icon-gengxinxiangmuxinxi' fontSize={16}
          onClick={() => {
            renderClick(data);
          }} />
      </div>
    </Popover>)
  }
  return (
    <div style={{ height: '100%', marginRight: "8px" }}>
      <DataGrid
        className='PaperDevSortableGrid'
        id='DataGridLoading'
        height='100%'
        ref={refProject}
        dataSource={appearanceData}
        keyExpr="sjxmbh"
        allowColumnReordering={true}
        allowColumnResizing={true}
        showRowLines={true}
        showColumnLines={true}
        showBorders={true}
        columnResizingMode="widget"
        hoverStateEnabled={true}
        // rowAlternationEnabled={true}
        onSelectionChanged={onSelectionData}
        scrolling={{ rowRenderingMode: 'virtual' }}
        selection={{ mode: 'single' }}

        selectedRowKeys={selRowKey}
        // loadPanel={{ enabled: true }}
        columnMinWidth={80}
        searchPanel={{ width: 220, visible: true, placeholder: '' }}
        groupPanel={{ visible: false }}
        grouping={{ autoExpandAll: true }}
        paging={{
          enabled: false
        }}
        rowAlternationEnabled={true}
      // pager={{
      //   visible: false,
      // }}
      >
        <Toolbar>
          <Item
            location='after'
            cssClass='NewButton'
          >
            <DropDownButton
              className='dxDropDownButton devDropDownButton'
              text='新建项目'
              displayExpr='name'
              keyExpr='id'
              // icon='add'
              dropDownOptions={{
                width: 120
              }}
              onItemClick={(e: any) => {
                if (e.itemData.template === 'items[0].template') {
                  selZcbfPopupRef.current.showSelZcbfPopup();
                } else if (e.itemData.template === 'items[1].template') {
                  setPopupTitle('单机建项');
                  localFormRef.current.showForm(false, '');
                }
              }}
            >
              <ButtonItem
                render={() => (<><CpasIcon type='icon-lianjijianxiang' fontSize={16} /> <span style={{ marginLeft: 10 }} >联机建项</span> </>)}
              />
              <ButtonItem
                render={() => (<><CpasIcon type='icon-danjijianxiang' fontSize={16} /> <span style={{ marginLeft: 10 }} >单机建项</span></>)}
              />
            </DropDownButton>
          </Item>
          <Item location="after" render={() => <div className='boxRight'></div>} />

          <Item location="after" name='searchPanel' />
          <Item location="after" render={() => <>
            {/* {showSpin ? <LoadIndicator id="medium-indicator" height={16} width={16} /> :
              <CpasIcon type='icon-refresh' fontSize={16}
                onClick={() => {
                  getList();
                }} />} */}
            <Button
              className="defaultReloadBtnWhite"
              render={() => (showSpin ? <LoadIndicator id="medium-indicator" height={16} width={16} /> :
                <CpasIcon type='icon-refresh' fontSize={16} />
              )}
              onClick={() => {
                getList();
              }} />
          </>
          } />
        </Toolbar>

        <Column
          caption={intl('pro.DataGrid.ProjectType', '项目类型')}
          dataField='XMType'
          groupIndex={0}
          cssClass=''
        />
        <Column
          caption={intl('pro.DataGrid.ProjectNumber', '项目编号')}
          dataField='projectBh'
          width={200}
        />
        <Column
          caption={intl('pro.DataGrid.ProjectName', '项目名称')}
          dataField='projectName'
        />
        <Column
          caption={intl('pro.DataGrid.ProjectManager', '项目经理')}
          dataField='manager'
        />
        <Column
          width={80}
          caption={intl('pro.TreeList.Operation', '操作')}
          alignment="center"
          allowResizing={false}
          fixed={true}
          fixedPosition='right'
          cellRender={(row: any) => (
            <div className='operationBox'>
              {renderCpasIcon(row)}
              <div className='hoverBac'>
                <CpasIcon type='icon-delete' fontSize={16}
                  onClick={async () => {
                    const { data } = row;
                    if (data.projectBh) {
                      const mapsData = getWindowsMapsList(data.projectBh);
                      if (mapsData) return notify({ message: `该项目已被打开，请勿删除！`, position: 'top center', width: 300 }, "warning", 2000);
                      const res = await getIsCheckProjectIsOpened({ projectBh: data.projectBh });
                      if (res.success) {
                        if (res.data) {
                          notify({ message: `该项目已被打开，请勿删除！`, position: 'top center', width: 300 }, "warning", 2000);
                        } else {
                          const res = await getZcbfID(data.projectBh);
                          if (res.ok) {
                            refsInputDialog.current.show({ projectBh: data.projectBh }, data.projectName, res.data);
                          }
                        }
                      }

                    } else {
                      notify({ message: `请选择项目！`, position: 'top center', width: 300 }, "warning", 1000);
                    }
                  }} />
              </div>
            </div>
          )}
        />
      </DataGrid>
      <SelZcbfPopupMemo ref={selZcbfPopupRef} />
      <NewLocalProject ref={localFormRef} getReloadList={async (formData: any) => {
        // 更新右侧的信息
        const tempData = {
          DBName: formData.sjxmbh,
          projectBh: formData.sjxmbh,
          projectName: formData.sjxmmc,
          sjxmbh: formData.sjxmbh,
          sjnd: formData.sjnd,
          projectState: 190,
          xmhhr: null,
          manager: curUser?.usercode,
          quality: null,
          XMType: "单机审计项目",
          bsdw: formData.bsdw,
          xmTimeEnd: formData.xmqje,
          xmTimeStart: formData.xmqjs
        }
        await getList();
        PubSub.publish('projectInfo', { msg: 'projectInfoData', data: tempData });
        setSelRowKey([formData.sjxmbh]);
      }} title={popupTitle} />

      <InputOKDialog ref={refsInputDialog} refreshTable={() => {
        getList();
        PubSub.publish('projectInfo', { msg: 'projectInfoDataDel', data: {} });
        setSelRowKey([]);
      }} />
    </div >
  );
};

export default ProjectArea;
